#!/usr/bin/python
# -*- coding: utf-8 -*-
import cgi, cgitb
cgitb.enable()

import socket
import re
import random
import time
pcl = re.compile(r"Content-Length: (.+?)\r\n")
def query(userid, passwd):
    sock1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock1.connect(("222.201.132.68",80))
    def process(request):
        sock.sendall(request)
        head = ""
        body = ""
        body_len = 0
        while True:
            t = sock.recv(4096)
            if "\r\n\r\n" in t:
                loc = t.find("\r\n\r\n")
                head += t[:loc+2]
                body += t[loc+4:]
                break
            else:
                head += t
        m = pcl.search(head)
        body_len = int(m.group(1))
      
        while (body_len!=len(body)):
            body += sock.recv(4096)

        return head, body
        
    url = "/("
    for i in range(24):
        url+=chr(random.randint(97,122))
    url += ")/default2.aspx"
    urlbase = url[:-14]

    __VIEWSTATE = "dDwtMTIwMTU3OTE3Nzs7PpB8l5/El8v0pRD42cfBxZlfb5jx"
    form = "TextBox1=%s&TextBox2=%s&__VIEWSTATE=%s&RadioButtonList1=%s&Button1=&lbLanguage=" % (userid, passwd, __VIEWSTATE, "%E5%AD%A6%E7%94%9F")
    post_str = """POST %s HTTP/1.1
Connetion: keep-alive
HOST: jw2005.scuteo.com
Content-Type: application/x-www-form-urlencoded
Content-Length: %d

%s
""" % (url, len(form), form)
    #process(post_str)
    sock1.sendall(post_str)
    time.sleep(0.1)
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.connect(("222.201.132.68",80))
    url = urlbase + "/xscjcx.aspx?xh=%s&gnmkdm=N121605" % (userid)
	
    get_str = """GET %s HTTP/1.1
Connetion: keep-alive
HOST: jw2005.scuteo.com
Referer: http://jw2005.scuteo.com

""" % (url)
    _, body = process(get_str)
    __VIEWSTATE = body.split('__VIEWSTATE" value="')[1].split('" />')[0].replace("+","%2B")
	
    form = "__VIEWSTATE=%s&btn_zcj=%s" % (__VIEWSTATE, "%C0%FA%C4%EA%B3%C9%BC%A8") 
    post_str = """POST %s HTTP/1.1
Connetion: keep-alive
HOST: jw2005.scuteo.com
Referer: http://jw2005.scuteo.com
Content-Type: application/x-www-form-urlencoded
Content-Length: %s

%s
""" % (url, len(form), form)
    for i in range(3):
        try:
            html = process(post_str)[1]
            table = html.split('tr class="datelisthead">')[1].split('</table>')[0].replace('<tr class="alt">', '<tr>').strip()[0:-5].replace("&nbsp;", "")
            trs = map(str.strip, table.split('</tr><tr>'))[1:]
            subjects = {}
            for tr in trs:
                tds = tr[4:-5].split('</td><td>')
                subjects[tds[2]]= [tds[3],tds[8]]
        except:
            pass
        else:
            break
    else:
        subjects = {}
    sock1.close()
    sock.close()
    

    return subjects
    
if __name__=="__main__":
    import time
    t = time.time()
    form = cgi.FieldStorage()

    userid = form.getvalue('userid')
    passwd = form.getvalue('passwd')
    print "Content-Type: text/html"
    print    
    subjects = {}
    try:
        subjects = query(userid, passwd)
    except:
	    pass
    print "<table>"
    for key,value in subjects.items():
        print "<tr>"
        print "<td>%s</td>" % key 
        print "<td>%s</td>" % value[0] 
        print "<td>%s</td>" % value[1]
        print "</tr>"
    print "</table>"
    print time.time()-t

#cgi.print_environ()


